package com.report.repository;

import com.report.entity.TableRowMapping;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface TableRowMappingRepository extends JpaRepository<TableRowMapping, Object> {

    @Query("SELECT p FROM TableRowMapping p WHERE p.projectNo = :projectNo order by p.id desc")
    List<TableRowMapping> getTableRowMappingByProjectNo(String projectNo);


    // 新增方法：根据projectNo、tName和rowName查找记录
    @Query("SELECT p FROM TableRowMapping p WHERE p.projectNo = :projectNo AND p.tName = :tName AND p.rowName = :rowName")
    TableRowMapping getTableRowMappingByProjectNoAndTNameAndRowName(String projectNo, String tName, String rowName);

    @Query("SELECT p FROM TableRowMapping p WHERE p.projectNo = :projectNo AND p.tName = :tName")
    List<TableRowMapping> getTableRowMappingByProjectNoAndTName(String projectNo, String tName);


    default TableRowMapping upsert(TableRowMapping tableRowMapping) {
        TableRowMapping existingRecord = getTableRowMappingByProjectNoAndTNameAndRowName(tableRowMapping.getProjectNo(), tableRowMapping.getTName(), tableRowMapping.getRowName());
        if (existingRecord != null) {
            existingRecord.setMapping(tableRowMapping.getMapping());
            return save(existingRecord);
        } else {
            return save(tableRowMapping);
        }
    }

}
